<template>
	<view class="main">
		<view class="msg_time" v-if="isTimeshow(msg.timestamp, lastTimestamp)">
			<view class="">
				<text>{{ formatMessageTime(msg.timestamp) }}</text>
			</view>
			<view class="">
				<text>{{ formatDistance(msg) }}</text>
			</view>
		</view>
		<view class="item" :id="`msgall-${msg.timestamp}`" :class="msg.userTel === storeData.user.userTel ? 'push' : 'pull'">
			<view class="" @click="toUser">
				<image v-if="msg.nicPic.url" :src="msg.nicPic.url" mode="aspectFill" class="pic"></image>
				<AvatarFallback v-else :name="msg.nicName"></AvatarFallback>
			</view>

			<view class="" style="display: flex; flex-direction: column">
				<view class="userId" v-if="msg.userTel !== storeData.user.userTel">
					{{ msg.nicName ? msg.nicName : msg.sendUserId }}
				</view>

				<view :class="msg.userTel === storeData.user.userTel ? 'push-content' : 'pull-content'" v-if="msg.messageType === 2" :id="`msg-${msg.timestamp}`">
					{{ msg.content.text }}
				</view>
				<view :class="msg.userTel === storeData.user.userTel ? 'push-content' : 'pull-content'" v-if="msg.messageType === 1" :id="`msg-${msg.timestamp}`">
					<view class="progress-bar" :style="{ width: (msg.content.duration < 6 ? 100 : msg.content.duration * 10) + 'rpx' }" @click.stop="handonPlay(msg)">
						{{ currentMsg === msg.timestamp ? progressedPercent.toFixed(0) + '%' : msg.content.duration + '秒' }}
						<view v-if="currentMsg === msg.timestamp" class="progress" :style="{ width: progressPercent + '%' }"></view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import formatMessageTime from '../utils/formatMessageTime';
import { VoicePlayer } from '../utils/VoicePlayer';
import { formatDistance } from '../utils/distance';
import AvatarFallback from './AvatarFallback.vue';
import setToTarget from '../utils/setTarget';
export default {
	name: 'textMsg',
	components: {
		AvatarFallback
	},
	props: {
		msg: {
			type: Object,
			default: () => {}
		},
		lastTimestamp: {
			type: Number,
			default: 0
		},
		progressPercent: {
			type: Number,
			default: 0,
		},
		msgList: {
			type: Array,
			default: () => []
		},
		currentMsg: {
			type: Number,
			default: -1
		}
	},

	data() {
		return {
			onPlay: false,
			playing: false,
			audioContext: null,
			stateConfig: { isPlaying: false, isplay: -1 },
			duration: 0,
			viewId: 0
		};
	},
	computed: {
		storeData() {
			return this.$store.state.msg;
		},
		progressedPercent(){
			return Math.min(100, Math.max(0, this.progressPercent));
		}
	},

	mounted() {},
	methods: {
		formatMessageTime,
		formatDistance(item) {
			return formatDistance(this.storeData.senderLocation, item);
		},

		isTimeshow(timestamp, lastTimestamp) {
			if (lastTimestamp > 0) {
				if (timestamp - lastTimestamp < 300000) {
					return false;
				} else if (!timestamp) {
					return false;
				} else {
					return true;
				}
			}
		},
		toUser() {
			console.log('///////');
			if (this.msg.sendUserId !== this.storeData.user.userId) {
				const queryParam = {};
				queryParam.id = this.msg.sendUserId;
				queryParam.type = 'person';
				this.$store.commit('msg/SET_queryParam', queryParam);
				setToTarget('person', { targetId: this.msg.sendUserId, nicName: this.msg.nicName, nicPic: this.msg.nicPic.url });

				uni.navigateTo({
					url: '/pages/messages/messages'
				});
			} else {
				uni.navigateTo({
					url: '/pages/me/me'
				});
			}
		},

		handonPlay(msg) {
			// 先停止当前播放
			if (this.currentMsg !== -1 && this.currentMsg !== msg.timestamp) {
				VoicePlayer.stop();
				this.onPlay = false;
				this.isPlaying = false;
			}

			// 查找当前消息在列表中的索引
			const index = this.msgList.findIndex((item) => item.timestamp === msg.timestamp);

			if (index === -1) {
				console.warn('未找到对应的消息');
				return;
			}

			// 切换播放状态
			this.onPlay = !this.onPlay;

			if (!this.onPlay) {
				this.isPlaying = false;
				VoicePlayer.stop();
			} else {
				this.isPlaying = true;
				VoicePlayer.play(this, index);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.main {
	width: 100%;
}
.userpic {
	display: flex;
	flex-direction: column;
	justify-content: flex-end;
	width: 60rpx;
	border-radius: 50%;
	margin-right: 32rpx;
}
.userId {
	display: flex;
	color: #a6a6a6;
	font-size: 22rpx;
	padding-left: 30rpx;
	padding-bottom: 5rpx;
}
.nicimg {
	width: 60rpx;
	height: 60rpx;
	border-radius: 30rpx;
}
.msg_time {
	display: flex;
	width: 100%;
	/* 1. 文本水平居中（margin:0 auto 是容器居中，text-align 是文本在容器内居中） */
	text-align: center;
	/* 2. 容器水平居中（配合 width:100% 确保占满父容器，margin 生效） */
	align-items: center;
	justify-content: center;
	margin-top: 15rpx;
	color: #969696;
	font-size: 24rpx;
	/* 3. 可选：限制时间戳背景，增强视觉区分 */
	padding: 5rpx 0;
	gap: 20rpx;
}
.item {
	padding: 15rpx 20rpx 15rpx 20rpx; // 上下各 15rpx 间距，左右保持 20rpx
	margin-bottom: 5rpx; // 可选：额外增加底部外边距，强化分隔
	align-items: flex-start;
	align-content: flex-start;
	color: #333;
	display: flex;
	flex-direction: row;
	flex-wrap: nowrap;
	justify-content: flex-start;
}

/* 收到的消息 */
.pull {
}

.pull-content {
	margin-left: 32rpx;
	background-color: #fff;
	padding: 15rpx;
	border-radius: 4px;
	max-width: 500rpx;
	word-break: break-all;
	line-height: 45rpx;
	position: relative;
	&::after {
		content: '';
		display: flex;
		width: 0;
		height: 0;
		border-top: 16rpx solid transparent;
		border-bottom: 16rpx solid transparent;
		border-right: 20rpx solid #fff;
		position: absolute;
		top: 30rpx;
		left: -18rpx;
	}
}
/* 发出的消息 */
.push {
	/* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
	flex-direction: row-reverse;
}
.push-content {
	flex-direction: row-reverse;
	margin-right: 32rpx;
	background-color: #a0e959;
	padding: 15rpx;
	border-radius: 4px;
	max-width: 500rpx;
	word-break: break-all;
	line-height: 45rpx;
	position: relative;
	&::after {
		content: '';
		display: flex;
		width: 0;
		height: 0;
		border-top: 16rpx solid transparent;
		border-bottom: 16rpx solid transparent;
		border-left: 20rpx solid #a0e959;
		position: absolute;
		top: 30rpx;
		right: -18rpx;
	}
}
.pic {
	width: 60rpx;
	height: 60rpx;
	border-radius: 15%;
	border: #e1e1e1 solid 1px;
}
.content {
	padding: 15rpx;
	border-radius: 4px;
	max-width: 500rpx;
	word-break: break-all;
	line-height: 45rpx;
	position: relative;
}
.progress-bar {
	text-align: center;
	font-size: 25rpx;
	color: #007bff;
	height: 100%;
	padding: 0;
	overflow: hidden;
}

.progress {
	height: 100%;
	background-color: #007bff;
	height: 8rpx;
}
</style>
